Page({
  data: {
    collects: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: true // 全选状态，默认全选
  },
  onShow() {
    this.setData({
      hasList: true, // 既然有数据了，那设为true吧
      collects: [{
          id: 1,
          title: '新鲜芹菜 半斤',
          image: '/image/s5.png',
          num: 4,
          price: 0.01,
          selected: true
        },
        {
          id: 2,
          title: '素米 500g',
          image: '/image/s6.png',
          num: 1,
          price: 0.03,
          selected: true
        }
      ]
    });
  },
  getTotalPrice() {
    let collects = this.data.collects; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < collects.length; i++) { // 循环列表得到每个数据
      if (collects[i].selected) { // 判断选中才会计算价格
        total += collects[i].num * collects[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      collects: collects,
      totalPrice: total.toFixed(2)
    });
  },
  selectList(e) {
    const index = e.currentTarget.dataset.index; // 获取data- 传进来的index
    let collects = this.data.collects; // 获取购物车列表
    const selected = collects[index].selected; // 获取当前商品的选中状态
    collects[index].selected = !selected; // 改变状态
    this.setData({
      collects: collects
    });
    this.getTotalPrice(); // 重新获取总价
  },
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus; // 是否全选状态
    selectAllStatus = !selectAllStatus;
    let collects = this.data.collects;

    for (let i = 0; i < collects.length; i++) {
      collects[i].selected = selectAllStatus; // 改变所有商品状态
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      collects: collects
    });
    this.getTotalPrice(); // 重新获取总价
  }, // 增加数量
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let collects = this.data.collects;
    let num = collects[index].num;
    num = num + 1;
    collects[index].num = num;
    this.setData({
      collects: collects
    });
    this.getTotalPrice();
  },
  // 减少数量
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let collects = this.data.collects;
    let num = collects[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    collects[index].num = num;
    this.setData({
      collects: collects
    });
    this.getTotalPrice();
  },
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let collects = this.data.collects;
    collects.splice(index, 1); // 删除购物车列表里这个商品
    this.setData({
      collects: collects
    });
    if (!collects.length) { // 如果购物车为空
      this.setData({
        hasList: false // 修改标识为false，显示购物车为空页面
      });
    } else { // 如果不为空
      this.getTotalPrice(); // 重新计算总价格
    }
  }


})